<?php

namespace service;

use app\common\model\Member;
use app\common\model\PayOrder;
use app\common\model\Users;
use think\Db;
use think\Exception;
use think\facade\Config;
use think\facade\Cookie;
use think\facade\Session;
use think\facade\Request;

class Auth
{

    protected static $instance = null;
    protected $_error = '';
    protected $_logined = FALSE;
    protected $_user = NULL;
    protected $_token = '';
    //Token默认有效时长
    protected $keeptime = 25920000;
    protected $requestUri = '';
    protected $rules = [];
    //默认配置
    protected $config = [];
    protected $options = [];
    protected $allowFields = ['name','nickname', 'mobile', 'avatar', 'score', 'headimg'];

    public function __construct($options = [])
    {
        if ($config = Config::get('user'))
        {
            $this->options = array_merge($this->config, $config);
        }
        $this->options = array_merge($this->config, $options);
    }

    /**
     * 
     * @param array $options 参数
     * @return Auth
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static($options);
        }
        return self::$instance;
    }

    /**
     * 获取User模型
     * @return User
     */
    public function getUser()
    {
        return $this->_user;
    }

    /**
     * 兼容调用user模型的属性
     * 
     * @param string $name
     * @return mixed
     */
    public function __get($name)
    {
        return $this->_user ? $this->_user->$name : NULL;
    }

    /**
     * 根据Token初始化
     *
     * @param string       $token    Token
     * @return boolean
     */
    public function init($token)
    {
        if ($this->_logined) {
            return true;
        }
        if ($this->_error){
            return false;
        }
        $data = Token::get($token);
        if (!$data) {
            return false;
        }
        $user_id = intval($data['user_id']);
        if ($user_id > 0) {
            $user = Users::get($user_id);
            if (!$user) {
                return false;
            }
            $this->_user = $user;
            $this->_logined = true;
            $this->_token = $token;
            return true;
        }else {
            return false;
        }
    }

    /**
     * 注册用户
     *
     * @param string $username  用户名
     * @param string $password  密码
     * @param string $email     邮箱
     * @param string $mobile    手机号
     * @return boolean
     */
    public function register($data)
    {
        $salt =  Random::alnum();
        $params = array_merge($data, [
            'salt'      => $salt,
            'ip'  => request()->ip()
        ]);
        $user_model = new Users();
        $params['password'] = $this->getEncryptPassword($data['passwd'], $params['salt']);
        unset($params['passwd']);

        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try{
            $user = Users::create($params);
            $spread_code = 'SC_'.date('ym').sprintf('%06d',$user->uid);
            if(isset($params['parent_id']) && $params['parent_id'] > 0) {
                $parent_user = Users::get($params['parent_id']);
                switch ($parent_user->identity_type) {
                    case Users::ORDINARY_USER:
                        $second_sum = Users::where('parent_id', $params['parent_id'])->count();
                        if($second_sum >= 3) {
                            $parent_user->identity_type = Users::PRIMARY_USER;
                            $parent_user->save();
                        }
                        break;
                    case Users::PRIMARY_USER:
                        $second_sum = Users::where('parent_id', $params['parent_id'])->count();
                        if($second_sum >= 53) {
                            $parent_user->identity_type = Users::INTERMEDIATE_USER;
                            $parent_user->save();
                        }
                        break;
                    case Users::INTERMEDIATE_USER:
                        $check_pay = PayOrder::where('commodity', 1)->where('uid', $params['parent_id'])->where('status', 2)->find();
                        if($check_pay) {
                            $second_sum = Users::where('parent_id', $params['parent_id'])->where('created_at', '>=', $check_pay->pay_at)->count();
                            if($second_sum >= 50) {
                                $parent_user->identity_type = Users::SENIOR_USER;
                            }
                        }else{
                            $second_sum = $second_sum = Users::where('parent_id', $params['parent_id'])->count();
                            if($second_sum >= 103) {
                                $parent_user->identity_type = Users::SENIOR_USER;
                            }
                        }
                        $parent_user->save();
                        break;
                    case Users::SENIOR_USER:
                        break;
                }
            }
            $user_model::update(['spread_code' => $spread_code,''],['uid' => $user->uid]);
            $this->direct($user->uid);
            Db::commit();
            return true;
        }catch (Exception $e){
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }


    /**
     * h5用户登录
     *
     * @param string    $mobile    手机号
     * @return boolean
     */
    public function webLogin($mobile)
    {
        if(!is_mobile($mobile)) {
            $this->setError('手机号输入错误');
            return false;
        }
        $user = Member::getByMobile($mobile);
        if(!$user) {

            return false;
        }
        //直接登录会员
        $this->direct($user->uid);
        return true;
    }

    /**
     * 用户登录
     *
     * @param string    $account    账号,用户名、邮箱、手机号
     * @param string    $password   密码
     * @return boolean
     */
    public function login($account, $password)
    {
        if(!is_mobile($account)) {
            $this->setError('手机号输入错误');
            return false;
        }
        $user = Users::getByMobile($account);
        if(!$user) {
            $this->setError('请先注册，然后登陆');
            return false;
        }
        if ($user->password != $this->getEncryptPassword($password, $user->salt) && env('APP_ENV') != 'debug') {
            $this->setError('账号或密码错误');
            return false;
        }
        //直接登录会员
        $this->direct($user->uid);
        return true;
    }

    /**
     * 注销
     * 
     * @return boolean
     */
    public function logout()
    {
        $token = Token::get($this->_token);
        if(isset($token['user_id']) && !empty($token['user_id'])) {
            Users::update(['token' => ''], ['uid' => $token['user_id']]);
        }
        //设置登录标识
        $this->_logined = false;
        //删除Token
        Token::delete($this->_token);
        return true;
    }

    /**
     * 修改密码
     * @param string    $newpassword        新密码
     * @param string    $oldpassword        旧密码
     * @param bool      $ignoreoldpassword  忽略旧密码
     * @return boolean
     */
    public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
    {
        if (!$this->_logined)
        {
            $this->setError('You are not logged in');
            return false;
        }
        //判断旧密码是否正确
        if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword)
        {
            $salt = Random::alnum();
            $newpassword = $this->getEncryptPassword($newpassword, $salt);
            $this->_user->save(['password' => $newpassword, 'salt' => $salt]);

            Token::delete($this->_token);
            return true;
        }
        else
        {
            $this->setError('Password is incorrect');
            return false;
        }
    }

    /**
     * 直接登录账号
     * @param int $user_id
     * @return boolean
     */
    public function direct($user_id)
    {
        $user = Users::get($user_id);
        if (!$user) {
            return false;
        }
        //判断连续登录和最大连续登录
        $token = Random::uuid();
        //记录本次登录的IP和时间
        $user->last_ip = request()->ip();
        $user->login_at = time();
        $user->token = $token;
        $user->save();
        $this->_token = $token;
        $this->_user = $user;
        Token::set($this->_token, $user_id, $this->keeptime);
        $this->_logined = true;

        Session::set(Config::get('session_web_user'), Token::get($this->_token));
        $this->keeplogin();
        //登录成功的事件
        return true;
    }

    /**
     * 判断是否登录
     * @return boolean
     */
    public function isLogin()
    {
        if ($this->_logined) {
            return true;
        }
        return false;
    }

    public function isUserType()
    {
        return $this->_usertype;
    }

    /**
     * 自动登录
     * @return boolean
     */
    public function autologin($token)
    {
        $keeplogin = Cookie::get(Config::get('keeplogin'));
        if (!$keeplogin) {
            return false;
        }
        list($user_id, $keeptime, $expiretime, $key) = implode('|', $keeplogin);
        if ($user_id && $keeptime && $expiretime && $key && $expiretime > time()) {
            $user = Users::get($user_id);
            if (!$user) {
                return false;
            }
            //token有变更
            if ($key != md5(md5($user_id) . md5($keeptime) . md5($expiretime) . $token)) {
                return false;
            }
            Session::set(Config::get('session_web_user'), Token::get($token));
            //刷新自动登录的时效
            $this->keeplogin($keeptime);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取当前Token
     * @return string
     */
    public function getToken()
    {
        return $this->_token;
    }

    /**
     * 刷新保持登录的Cookie
     *
     * @param   int $keeptime
     * @return  boolean
     */
    protected function keeplogin($keeptime = 86400)
    {
        $data = Token::get($this->_token);
        if(time() > $data['expiretime']) {
            $expiretime = time() + $keeptime;
            $key = md5(md5($data['user_id']) . md5($data['user_type']) . md5($keeptime) . md5($expiretime) . $data['token']);
            $param = [$data['user_id'] ,$data['user_type'], $keeptime, $expiretime, $key];
            Cookie::set(Config::get('keeplogin'), implode('|', $param), 86400 * 30);
            return true;
        }
        return false;
    }

    /**
     * 获取会员基本信息
     */
    public function getUserinfo()
    {
        $data = $this->_user->toArray();
        $allowFields = $this->getAllowFields();
        $userinfo = array_intersect_key($data, array_flip($allowFields));
        $userinfo = array_merge($userinfo, Token::get($this->_token));
        return $userinfo;
    }


    /**
     * 获取当前请求的URI
     * @return string
     */
    public function getRequestUri()
    {
        return $this->requestUri;
    }

    /**
     * 设置当前请求的URI
     * @param string $uri
     */
    public function setRequestUri($uri)
    {
        $this->requestUri = $uri;
    }

    /**
     * 获取允许输出的字段
     * @return array
     */
    public function getAllowFields()
    {
        return $this->allowFields;
    }

    /**
     * 设置允许输出的字段
     * @param array $fields
     */
    public function setAllowFields($fields)
    {
        $this->allowFields = $fields;
    }

    /**
     * 删除一个指定会员
     * @param int $user_id 会员ID
     * @return boolean
     */
    public function delete($user_id)
    {
        $user = Users::get($user_id);
        if (!$user)
        {
            return FALSE;
        }


        // 调用事务删除账号
        $result = Db::transaction(function($db) use($user_id) {
                    // 删除会员
                    Users::destroy($user_id);
                    // 删除会员指定的所有Token
                    Token::clear($user_id);
                    return TRUE;
                });
        if ($result)
        {
        }
        return $result ? TRUE : FALSE;
    }

    /**
     * 获取密码加密后的字符串
     * @param string $password  密码
     * @param string $salt      密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     * @return boolean
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr)
        {
            return FALSE;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr))
        {
            return TRUE;
        }
        // 没找到匹配
        return FALSE;
    }

    /**
     * 设置会话有效时间
     * @param int $keeptime 默认为永久
     */
    public function keeptime($keeptime = 0)
    {
        $expiretime = time() + $keeptime;
        $key = md5(md5($this->_user['user_id']) . md5($keeptime) . md5($expiretime) . $this->_token);
        $data = [$this->id, $keeptime, $expiretime, $key];
        Cookie::set('keeplogin', implode('|', $data), 86400 * 30);
        return true;
    }

    /**
     * 渲染用户数据
     * @param array     $datalist   二维数组
     * @param mixed     $fields     加载的字段列表
     * @param string    $fieldkey   渲染的字段
     * @param string    $renderkey  结果字段
     * @return array
     */
    public function render(&$datalist, $fields = [], $fieldkey = 'user_id', $renderkey = 'userinfo')
    {
        $fields = !$fields ? ['id', 'nickname', 'level', 'avatar'] : (is_array($fields) ? $fields : explode(',', $fields));
        $ids = [];
        foreach ($datalist as $k => $v)
        {
            if (!isset($v[$fieldkey]))
                continue;
            $ids[] = $v[$fieldkey];
        }
        $list = [];
        if ($ids)
        {
            if (!in_array('id', $fields))
            {
                $fields[] = 'id';
            }
            $ids = array_unique($ids);
            $selectlist = Users::where('id', 'in', $ids)->column($fields);
            foreach ($selectlist as $k => $v)
            {
                $list[$v['id']] = $v;
            }
        }
        foreach ($datalist as $k => &$v)
        {
            $v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : NULL;
        }
        unset($v);
        return $datalist;
    }

    /**
     * 设置错误信息
     *
     * @param $error 错误信息
     * @return Auth
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error ? $this->_error : '';
    }

}
